/*********************************************************************************
 * Copyright (C) 2011-2013 X2Engine Inc. All Rights Reserved.
 * 
 * X2Engine Inc.
 * P.O. Box 66752
 * Scotts Valley, California 95067 USA
 * 
 * Company website: http://www.x2engine.com 
 * Community and support website: http://www.x2community.com 
 * 
 * X2Engine Inc. grants you a perpetual, non-exclusive, non-transferable license 
 * to install and use this Software for your internal business purposes.  
 * You shall not modify, distribute, license or sublicense the Software.
 * Title, ownership, and all intellectual property rights in the Software belong 
 * exclusively to X2Engine.
 * 
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EITHER 
 * EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 ********************************************************************************/


/* @edition:pro */


function WebleadFormDesignerPro (argsDict) {
	WebFormDesignerPro.call (this, argsDict);	
}

WebleadFormDesignerPro.prototype = auxlib.create (WebFormDesignerPro.prototype);

/*
Public static methods
*/

/*
Private static methods
*/


/*
Public instance methods
*/

/*
Private instance methods
*/

/*
Append additional query parameters
*/
WebleadFormDesignerPro.prototype._appendToQuery = function (query) {

    var fieldList = this._getFieldList ();
    
    if($.inArray ('?', query) >= 0) {
        query += '&';
    } else {
        query += '?';
    }

    // set POST data for saving weblead form
    $('#fieldList').val(encodeURIComponent(JSON.stringify(fieldList))); 

    query += 'fieldlist=' + encodeURIComponent(JSON.stringify(fieldList));
    query += '&css=' + encodeURIComponent($('#custom-css').val());
    query += '&header=' + encodeURIComponent($('#saved-forms').val());
    query += '&user_email_template=' + encodeURIComponent($('#user-email-template').val());
    query += '&weblead_email_template=' + encodeURIComponent($('#weblead-email-template').val());
    return query;
};

/*
Clear form input
*/
WebleadFormDesignerPro.prototype._clearFields = function () {
    var that = this;
    $('#web-form-name').val('');
    $('#custom-html').val('');
    $('#custom-css').val('');
    $.each(that.fields, function(i, field) {
        $('#'+field).val('');
    });
};

/*
Insert form input
*/
WebleadFormDesignerPro.prototype._updateExtraFields = function (form) {

    if(typeof form.css !== 'undefined') {
        $('#custom-css').val(form.css);
    }
    if(typeof form.header !== 'undefined') {
        $('#custom-html').val(form.header);
    }
    if(typeof form.userEmailTemplate !== 'undefined') {
        $('#user-email-template').val(form.userEmailTemplate);
    }
    if(typeof form.webleadEmailTemplate !== 'undefined') {
        $('#weblead-email-template').val(form.userEmailTemplate);
    }
};

WebleadFormDesignerPro.prototype._beforeSaved = function () {
    $('#add-custom-html-button').removeClass ('highlight');
    auxlib.destroyErrorBox ($('#custom-html-input-container'));
};

WebleadFormDesignerPro.prototype._afterSavedFormsChange = function () {
    auxlib.destroyErrorBox ($('#custom-html-input-container'));
    $('#add-custom-html-button').removeClass ('highlight');
};

WebFormDesignerPro.prototype._afterInit = function () {
    var that = this;

    $('#custom-css, #user-email-template, #weblead-email-template').on('change', function() {
        that.updateParams();
    });

    /*
    Indicate to user that they have changes to save
    */
    $('#custom-html').on('keydown change', function(evt) {
        x2.DEBUG && console.log ('change'); 
        if (validateCustomHtml (true)) {
            $('#add-custom-html-button').addClass ('highlight');
        } else {
            $('#add-custom-html-button').removeClass ('highlight');
        }
    });

    /*
    Return true if custom html can be saved, false otherwise. Display validation error messages
    unless suppressErrorBox is set to true.
    */
    function validateCustomHtml (suppressErrorBox) {
        suppressErrorBox = typeof suppressErrorBox === 'undefined' ? false : true;

        // check if a saved form is selected
        var formIsSaved = $('#saved-forms').val () === '0' ? false : true;
        x2.DEBUG && console.log ('formIsSaved = ' + formIsSaved);

        var isValid = true;
    
        if (!formIsSaved) {
            if (!auxlib.errorBoxExists ($('#custom-html-input-container')) &&
                !suppressErrorBox) {
                $('#custom-html-input-container').append (
                    auxlib.createErrorBox ("", 
                        [that.translations[
                            "Custom HTML cannot be added to the web form until it has been " +
                            "saved."]]));
            }
            isValid = false;
        } else if ($('#custom-html').val () === '') {
            if (!auxlib.errorBoxExists ($('#custom-html-input-container')) &&
                !suppressErrorBox) {
                $('#custom-html-input-container').append (
                    auxlib.createErrorBox (
                        "", [that.translations["HTML cannot be empty."]]));
            }
            isValid = false;
        } else {
            x2.DEBUG && console.log ('destroyErrorBox');
            auxlib.destroyErrorBox ($('#custom-html-input-container'));
        }
        return isValid;

    }

    /*
    Clear custom html textarea and save changes to database, if a record exists
    */
    $('#remove-custom-html-button').on('click', function(evt) {
        evt.stopPropagation ();
        html: $('#custom-html').val ('');
        if ($('#saved-forms').val () !== '0') {
            $.ajax ({
                url: yii.scriptUrl + '/marketing/removeWebLeadFormCustomHtml',
                type: 'POST',
                data: {
                    id: $('#saved-forms').val (),
                },
                success: function (data) {
                    var data = JSON.parse (data);
                    if (data[0] === 'failure') {
                        $('#custom-html-input-container').append (
                            auxlib.createErrorBox ("", [data[1]]));
                    }  else {
                        that._cacheSavedForm (data[1]);
                        that.updateParams();
                        auxlib.createReqFeedbackBox ({
                            prevElem: $('#remove-custom-html-button'), 
                            message: that.translations["HTML removed"],
                            disableButton: $('#remove-custom-html-button'),
                            classes: ['save-html-feedback']
                        });
                    }
                }
            });
        }
        auxlib.destroyErrorBox ($('#custom-html-input-container'));
        $('#add-custom-html-button').removeClass ('highlight');
        return false;
    });

    /*
    Validate custom html input. If valid, save html to web lead form record and update iframe
    src attribute with web lead form record id.
    */
    $('#add-custom-html-button').on('click', function(evt) {
        evt.stopPropagation ();
        x2.DEBUG && console.log ('click');

        if (validateCustomHtml ()) {
            $.ajax ({
                url: yii.scriptUrl + '/marketing/saveWebLeadFormCustomHtml',
                type: 'POST',
                data: {
                    id: $('#saved-forms').val (),
                    html: $('#custom-html').val ()
                },
                success: function (data) {
                    var data = JSON.parse (data);
                    x2.DEBUG && console.log (data);
                    if (data[0] === 'error') {
                        $('#custom-html-input-container').append (
                            auxlib.createErrorBox ("", [data[1]]));
                    } else {
                        $('#add-custom-html-button').removeClass ('highlight');
                        that.updateParams();
                        auxlib.createReqFeedbackBox ({
                            prevElem: $('#remove-custom-html-button'), 
                            message: that.translations["HTML saved"],
                            disableButton: $('#add-custom-html-button'),
                            classes: ['save-html-feedback']
                        });
                        that._cacheSavedForm (data[1]);
                    }
                }
            });
    
        }
        return false;
    });

    WebFormDesignerPro._enableTabsForCustomCss ();
    WebFormDesignerPro._setUpSortableCustomFieldsBehavior (that);

};


